<template>
  <div class="pin-input-wrapper display-flex" :class="[inputSize]">
    <pin-field
      ref="pinInputRef"
      :="props"
      @focus="handleFocus"
      @blur="handleBlur"
    ></pin-field>
  </div>
</template>

<script setup lang="ts">
import { computed, unref, useTemplateRef, watch } from 'vue'
import type {
  WrapperProsp,
  WrapperEmits,
  PinFieldEmits,
  PinFieldExposes
} from './types'
import PinField from './PinField.vue'

const props = withDefaults(defineProps<WrapperProsp>(), {
  modelValue: () => ['', '', '', ''],
  error: false,
  readonly: false,
  size: 'default',
  placeholder: '○',
  disabled: false,
  mask: false,
  otp: false,
  type: 'text'
})

const emits = defineEmits<WrapperEmits & PinFieldEmits>()

const inputSize = computed(() => {
  const { size } = props
  return `pin-field--${size}`
})

const handleFocus = (index: number) => {
  emits('focus', index)
}
const handleBlur = (index: number) => {
  emits('blur', index)
}

const isComplete = computed(() => {
  const { modelValue } = props
  const values = props.modelValue.filter((item) => !!item)
  return values.length === modelValue.length
})

watch(
  () => props.modelValue,
  () => {
    if (isComplete.value) {
      emits('complete', props.modelValue)
    } else {
      emits('incomplete', props.modelValue)
    }
  },
  { deep: true }
)

const pinInputRef = useTemplateRef<InstanceType<typeof PinField>>('pinInputRef')

defineExpose<PinFieldExposes>({
  clear() {
    props.modelValue.forEach((_, index) => {
      props.modelValue[index] = ''
    })
  },
  blur(index = 0) {
    const pinInputEl = unref(pinInputRef)
    if (pinInputEl?.el && pinInputEl?.el[index]) pinInputEl.el[index].blur()
  },
  focus(index = 0) {
    const pinInputEl = unref(pinInputRef)
    if (pinInputEl?.el && pinInputEl?.el[index]) pinInputEl.el[index].focus()
  }
})

defineOptions({
  name: 'CorePinInput'
})
</script>

<style scoped lang="scss">
.pin-input-wrapper {
  position: relative;
  width: fit-content;
  height: var(--el-component-size);
  font-size: 14px;

  &.pin-field--large {
    height: var(--el-component-size-large);

    :deep(.pin-field) {
      width: calc(var(--el-component-size-large) - 2px);
    }
  }

  &.pin-field--small {
    height: var(--el-component-size-small);
    font-size: 12px;

    :deep(.pin-field) {
      width: calc(var(--el-component-size-small) - 2px);
    }
  }
}
</style>
